package com.gm.census.service.impl;

import java.util.List;
import java.util.logging.Logger;

import com.gm.census.model.pojo.Congregation;
import com.gm.census.model.pojo.User;
import com.gm.census.service.BaseService;
import com.gm.census.service.UserService;
import com.google.appengine.api.datastore.Cursor;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class UserServiceImpl extends BaseServiceImpl<User, String> implements
		UserService {

	static {
		ObjectifyService.register(User.class);
	}

	private static final Logger log = Logger.getLogger(UserServiceImpl.class
			.getName());

	@Override
	public User find(final String id) {
		return inNs(new DefaultNSCmd<User>() {

			@Override
			public User execute() {
				return begin().find(User.class, id);
			}

		});
	}

	@Override
	public User put(final User usr) {
		User rusr = inNs(new DefaultNSCmd<User>() {

			@Override
			public User execute() {
				usr.setCongregationId(new Key<Congregation>(Congregation.class,usr.getCongregation().getId()));
				Key<User> k = begin().put(usr);
				usr.setId(k.getName());
				return usr;
			}

		});
		return rusr;
	}

	@Override
	public void delete(final String id) {
		inNs(new DefaultNSCmd<User>() {
			
			@Override
			public User execute() {
				begin().delete(User.class, id);
				return null;
			}

		});
	}

	@Override
	public User get(final String id) {
		User usr = inNs(new DefaultNSCmd<User>() {

			@Override
			public User execute() {
				User u = begin().get(User.class, id);
				return u;
			}

		});
		return usr;
	}

	@Override
	public List<User> list() {
		return inNs(new DefaultNSCmd<List<User>>() {

			@Override
			public List<User> execute() {
				return begin().query(User.class)
						.limit(BaseService.DEFAULT_QUERY_PAGE).list();
			}

		});
	}

	@Override
	public GAEPagedListResult<User> list(final String index,
			final Integer pageSize) {
		return inNs(new DefaultNSCmd<GAEPagedListResult<User>>() {

			@Override
			public GAEPagedListResult<User> execute() {
				Query<User> q = begin().query(User.class);
				if (pageSize > 0)
					q.limit(pageSize);
				else
					q.limit(BaseService.DEFAULT_QUERY_PAGE);

				if (index != null && index.length() > 0) {
					Cursor cursor = Cursor.fromWebSafeString(index);
					q.startCursor(cursor);
				}

				return new GAEPagedListResult<User>(q.iterator());
			}

		});
	}

	@Override
	public GAEPagedListResult<User> list(String index) {
		return list(index, 0);
	}

}
